git.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. # The following comment should be removed at some point in the future.
  2. # mypy: disallow-untyped-defs=False
  3. from __future__ import absolute_import
  4. import logging
  5. import os.path
  6. import re
  7. from pip._vendor.packaging.version import parse as parse_version
  8. from pip._vendor.six.moves.urllib import parse as urllib_parse
  9. from pip._vendor.six.moves.urllib import request as urllib_request
  10. from pip._internal.exceptions import BadCommand, SubProcessError
  11. from pip._internal.utils.misc import display_path, hide_url
  12. from pip._internal.utils.subprocess import make_command
  13. from pip._internal.utils.temp_dir import TempDirectory
  14. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  15. from pip._internal.vcs.versioncontrol import (
  16. RemoteNotFoundError,
  17. VersionControl,
  18. find_path_to_setup_from_repo_root,
  19. vcs,
  20. )
  21. if MYPY_CHECK_RUNNING:
  22. from typing import Optional, Tuple
  23. from pip._internal.utils.misc import HiddenText
  24. from pip._internal.vcs.versioncontrol import AuthInfo, RevOptions
  25. urlsplit = urllib_parse.urlsplit
  26. urlunsplit = urllib_parse.urlunsplit
  27. logger = logging.getLogger(__name__)
  28. HASH_REGEX = re.compile('^[a-fA-F0-9]{40}$')
  29. def looks_like_hash(sha):
  30. return bool(HASH_REGEX.match(sha))
  31. class Git(VersionControl):
  32. name = 'git'
  33. dirname = '.git'
  34. repo_name = 'clone'
  35. schemes = (
  36. 'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file',
  37. )
  38. # Prevent the user's environment variables from interfering with pip:
  39. # https://github.com/pypa/pip/issues/1130
  40. unset_environ = ('GIT_DIR', 'GIT_WORK_TREE')
  41. default_arg_rev = 'HEAD'
  42. @staticmethod
  43. def get_base_rev_args(rev):
  44. return [rev]
  45. def is_immutable_rev_checkout(self, url, dest):
  46. # type: (str, str) -> bool
  47. _, rev_options = self.get_url_rev_options(hide_url(url))
  48. if not rev_options.rev:
  49. return False
  50. if not self.is_commit_id_equal(dest, rev_options.rev):
  51. # the current commit is different from rev,
  52. # which means rev was something else than a commit hash
  53. return False
  54. # return False in the rare case rev is both a commit hash
  55. # and a tag or a branch; we don't want to cache in that case
  56. # because that branch/tag could point to something else in the future
  57. is_tag_or_branch = bool(
  58. self.get_revision_sha(dest, rev_options.rev)[0]
  59. )
  60. return not is_tag_or_branch
  61. def get_git_version(self):
  62. VERSION_PFX = 'git version '
  63. version = self.run_command(['version'])
  64. if version.startswith(VERSION_PFX):
  65. version = version[len(VERSION_PFX):].split()[0]
  66. else:
  67. version = ''
  68. # get first 3 positions of the git version because
  69. # on windows it is x.y.z.windows.t, and this parses as
  70. # LegacyVersion which always smaller than a Version.
  71. version = '.'.join(version.split('.')[:3])
  72. return parse_version(version)
  73. @classmethod
  74. def get_current_branch(cls, location):
  75. """
  76. Return the current branch, or None if HEAD isn't at a branch
  77. (e.g. detached HEAD).
  78. """
  79. # git-symbolic-ref exits with empty stdout if "HEAD" is a detached
  80. # HEAD rather than a symbolic ref. In addition, the -q causes the
  81. # command to exit with status code 1 instead of 128 in this case
  82. # and to suppress the message to stderr.
  83. args = ['symbolic-ref', '-q', 'HEAD']
  84. output = cls.run_command(
  85. args, extra_ok_returncodes=(1, ), cwd=location,
  86. )
  87. ref = output.strip()
  88. if ref.startswith('refs/heads/'):
  89. return ref[len('refs/heads/'):]
  90. return None
  91. def export(self, location, url):
  92. # type: (str, HiddenText) -> None
  93. """Export the Git repository at the url to the destination location"""
  94. if not location.endswith('/'):
  95. location = location + '/'
  96. with TempDirectory(kind="export") as temp_dir:
  97. self.unpack(temp_dir.path, url=url)
  98. self.run_command(
  99. ['checkout-index', '-a', '-f', '--prefix', location],
  100. cwd=temp_dir.path
  101. )
  102. @classmethod
  103. def get_revision_sha(cls, dest, rev):
  104. """
  105. Return (sha_or_none, is_branch), where sha_or_none is a commit hash
  106. if the revision names a remote branch or tag, otherwise None.
  107. Args:
  108. dest: the repository directory.
  109. rev: the revision name.
  110. """
  111. # Pass rev to pre-filter the list.
  112. output = ''
  113. try:
  114. output = cls.run_command(['show-ref', rev], cwd=dest)
  115. except SubProcessError:
  116. pass
  117. refs = {}
  118. for line in output.strip().splitlines():
  119. try:
  120. sha, ref = line.split()
  121. except ValueError:
  122. # Include the offending line to simplify troubleshooting if
  123. # this error ever occurs.
  124. raise ValueError('unexpected show-ref line: {!r}'.format(line))
  125. refs[ref] = sha
  126. branch_ref = 'refs/remotes/origin/{}'.format(rev)
  127. tag_ref = 'refs/tags/{}'.format(rev)
  128. sha = refs.get(branch_ref)
  129. if sha is not None:
  130. return (sha, True)
  131. sha = refs.get(tag_ref)
  132. return (sha, False)
  133. @classmethod
  134. def resolve_revision(cls, dest, url, rev_options):
  135. # type: (str, HiddenText, RevOptions) -> RevOptions
  136. """
  137. Resolve a revision to a new RevOptions object with the SHA1 of the
  138. branch, tag, or ref if found.
  139. Args:
  140. rev_options: a RevOptions object.
  141. """
  142. rev = rev_options.arg_rev
  143. # The arg_rev property's implementation for Git ensures that the
  144. # rev return value is always non-None.
  145. assert rev is not None
  146. sha, is_branch = cls.get_revision_sha(dest, rev)
  147. if sha is not None:
  148. rev_options = rev_options.make_new(sha)
  149. rev_options.branch_name = rev if is_branch else None
  150. return rev_options
  151. # Do not show a warning for the common case of something that has
  152. # the form of a Git commit hash.
  153. if not looks_like_hash(rev):
  154. logger.warning(
  155. "Did not find branch or tag '%s', assuming revision or ref.",
  156. rev,
  157. )
  158. if not rev.startswith('refs/'):
  159. return rev_options
  160. # If it looks like a ref, we have to fetch it explicitly.
  161. cls.run_command(
  162. make_command('fetch', '-q', url, rev_options.to_args()),
  163. cwd=dest,
  164. )
  165. # Change the revision to the SHA of the ref we fetched
  166. sha = cls.get_revision(dest, rev='FETCH_HEAD')
  167. rev_options = rev_options.make_new(sha)
  168. return rev_options
  169. @classmethod
  170. def is_commit_id_equal(cls, dest, name):
  171. """
  172. Return whether the current commit hash equals the given name.
  173. Args:
  174. dest: the repository directory.
  175. name: a string name.
  176. """
  177. if not name:
  178. # Then avoid an unnecessary subprocess call.
  179. return False
  180. return cls.get_revision(dest) == name
  181. def fetch_new(self, dest, url, rev_options):
  182. # type: (str, HiddenText, RevOptions) -> None
  183. rev_display = rev_options.to_display()
  184. logger.info('Cloning %s%s to %s', url, rev_display, display_path(dest))
  185. self.run_command(make_command('clone', '-q', url, dest))
  186. if rev_options.rev:
  187. # Then a specific revision was requested.
  188. rev_options = self.resolve_revision(dest, url, rev_options)
  189. branch_name = getattr(rev_options, 'branch_name', None)
  190. if branch_name is None:
  191. # Only do a checkout if the current commit id doesn't match
  192. # the requested revision.
  193. if not self.is_commit_id_equal(dest, rev_options.rev):
  194. cmd_args = make_command(
  195. 'checkout', '-q', rev_options.to_args(),
  196. )
  197. self.run_command(cmd_args, cwd=dest)
  198. elif self.get_current_branch(dest) != branch_name:
  199. # Then a specific branch was requested, and that branch
  200. # is not yet checked out.
  201. track_branch = 'origin/{}'.format(branch_name)
  202. cmd_args = [
  203. 'checkout', '-b', branch_name, '--track', track_branch,
  204. ]
  205. self.run_command(cmd_args, cwd=dest)
  206. #: repo may contain submodules
  207. self.update_submodules(dest)
  208. def switch(self, dest, url, rev_options):
  209. # type: (str, HiddenText, RevOptions) -> None
  210. self.run_command(
  211. make_command('config', 'remote.origin.url', url),
  212. cwd=dest,
  213. )
  214. cmd_args = make_command('checkout', '-q', rev_options.to_args())
  215. self.run_command(cmd_args, cwd=dest)
  216. self.update_submodules(dest)
  217. def update(self, dest, url, rev_options):
  218. # type: (str, HiddenText, RevOptions) -> None
  219. # First fetch changes from the default remote
  220. if self.get_git_version() >= parse_version('1.9.0'):
  221. # fetch tags in addition to everything else
  222. self.run_command(['fetch', '-q', '--tags'], cwd=dest)
  223. else:
  224. self.run_command(['fetch', '-q'], cwd=dest)
  225. # Then reset to wanted revision (maybe even origin/master)
  226. rev_options = self.resolve_revision(dest, url, rev_options)
  227. cmd_args = make_command('reset', '--hard', '-q', rev_options.to_args())
  228. self.run_command(cmd_args, cwd=dest)
  229. #: update submodules
  230. self.update_submodules(dest)
  231. @classmethod
  232. def get_remote_url(cls, location):
  233. """
  234. Return URL of the first remote encountered.
  235. Raises RemoteNotFoundError if the repository does not have a remote
  236. url configured.
  237. """
  238. # We need to pass 1 for extra_ok_returncodes since the command
  239. # exits with return code 1 if there are no matching lines.
  240. stdout = cls.run_command(
  241. ['config', '--get-regexp', r'remote\..*\.url'],
  242. extra_ok_returncodes=(1, ), cwd=location,
  243. )
  244. remotes = stdout.splitlines()
  245. try:
  246. found_remote = remotes[0]
  247. except IndexError:
  248. raise RemoteNotFoundError
  249. for remote in remotes:
  250. if remote.startswith('remote.origin.url '):
  251. found_remote = remote
  252. break
  253. url = found_remote.split(' ')[1]
  254. return url.strip()
  255. @classmethod
  256. def get_revision(cls, location, rev=None):
  257. if rev is None:
  258. rev = 'HEAD'
  259. current_rev = cls.run_command(
  260. ['rev-parse', rev], cwd=location,
  261. )
  262. return current_rev.strip()
  263. @classmethod
  264. def get_subdirectory(cls, location):
  265. """
  266. Return the path to setup.py, relative to the repo root.
  267. Return None if setup.py is in the repo root.
  268. """
  269. # find the repo root
  270. git_dir = cls.run_command(
  271. ['rev-parse', '--git-dir'],
  272. cwd=location).strip()
  273. if not os.path.isabs(git_dir):
  274. git_dir = os.path.join(location, git_dir)
  275. repo_root = os.path.abspath(os.path.join(git_dir, '..'))
  276. return find_path_to_setup_from_repo_root(location, repo_root)
  277. @classmethod
  278. def get_url_rev_and_auth(cls, url):
  279. # type: (str) -> Tuple[str, Optional[str], AuthInfo]
  280. """
  281. Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
  282. That's required because although they use SSH they sometimes don't
  283. work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
  284. parsing. Hence we remove it again afterwards and return it as a stub.
  285. """
  286. # Works around an apparent Git bug
  287. # (see https://article.gmane.org/gmane.comp.version-control.git/146500)
  288. scheme, netloc, path, query, fragment = urlsplit(url)
  289. if scheme.endswith('file'):
  290. initial_slashes = path[:-len(path.lstrip('/'))]
  291. newpath = (
  292. initial_slashes +
  293. urllib_request.url2pathname(path)
  294. .replace('\\', '/').lstrip('/')
  295. )
  296. url = urlunsplit((scheme, netloc, newpath, query, fragment))
  297. after_plus = scheme.find('+') + 1
  298. url = scheme[:after_plus] + urlunsplit(
  299. (scheme[after_plus:], netloc, newpath, query, fragment),
  300. )
  301. if '://' not in url:
  302. assert 'file:' not in url
  303. url = url.replace('git+', 'git+ssh://')
  304. url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
  305. url = url.replace('ssh://', '')
  306. else:
  307. url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
  308. return url, rev, user_pass
  309. @classmethod
  310. def update_submodules(cls, location):
  311. if not os.path.exists(os.path.join(location, '.gitmodules')):
  312. return
  313. cls.run_command(
  314. ['submodule', 'update', '--init', '--recursive', '-q'],
  315. cwd=location,
  316. )
  317. @classmethod
  318. def get_repository_root(cls, location):
  319. loc = super(Git, cls).get_repository_root(location)
  320. if loc:
  321. return loc
  322. try:
  323. r = cls.run_command(
  324. ['rev-parse', '--show-toplevel'],
  325. cwd=location,
  326. log_failed_cmd=False,
  327. )
  328. except BadCommand:
  329. logger.debug("could not determine if %s is under git control "
  330. "because git is not available", location)
  331. return None
  332. except SubProcessError:
  333. return None
  334. return os.path.normpath(r.rstrip('\r\n'))
  335. vcs.register(Git)